import Taro, { Component } from '@tarojs/taro'
import { View , Text , Image , Map , ScrollView } from '@tarojs/components';
import { baseTxKey , baseImgSrc} from '../../util/base_url';
import { AtButton , AtIndexes , AtInput } from 'taro-ui';
import QQMapWX from '../../util/qqmap-wx-jssdk.min.js';
import { cityData } from '../../util/city.js';
import './map.scss';
export default class TxMap extends Component{
    constructor(){
        super();
        this.state = {
            latitude:"",
            longitude:"",
            address:"",
            city:"获取中",
            lastPargeParam:"",
            listOpen:false,
            oftAddress:[],
            oftStatus:false,
        }
    }
    onTap(){

    }
    onMapMove(e){
        if (e.type == 'end' && (e.causedBy == 'scale' || e.causedBy == 'drag')) {
            var _this = this;
            _this.setCenterLocal();
            _this.setState({oftStatus:false})
        }
    }
    componentDidShow(){
        this.setState({lastPargeParam:this.$router.params.iden})
    }
    componentWillMount(){
        this.initMap(); //初始化地图
    }
    componentWillUnmount(){
        if(this.state.listOpen){
           this.setState({listOpen:false});
           return false
        }
        return false
    }
    onAddressChange(address){
        this.setState({address});
        // clearTimeout(this.timp)
        this.searchOftAddress(address)
        return address
    }
    searchOftAddress(keyword){
        let { city } = this.state;
        let _this = this;
        this.qqmapsdk.getSuggestion({
            //获取输入框值并设置keyword参数
            keyword, //用户输入的关键词，可设置固定值,如keyword:'KFC'
            region:city, //设置城市名，限制关键词所示的地域范围，非必填参数
            page_size:5,
            success: function(res) {//搜索成功后的回调
               _this.setState({oftAddress:res.data,oftStatus:true})
            },
        });
    }
    clickOftAddress(address,latitude,longitude){
        this.setState({address,latitude,longitude},() => {
            setTimeout(() => {
                this.setState({oftStatus:false})
            },200)
        })
    }
    onCityItem(item){ //地址点击
        this.setState({
            listOpen:false,
            city:item.name,
        })
        this.AddressToll(item.name);
    }
    selectCity(){
        this.setState({
            listOpen:true,
        })
    }
    closeCity(){
        this.setState({ listOpen:false })
    }
    initMap(){
        var _this = this;
        _this.qqmapsdk = new QQMapWX({
            key: baseTxKey,
        });
        Taro.getLocation({
            type: 'wgs84',
            success: function (res) {
                const latitude = res.latitude;
                const longitude = res.longitude;
                _this.setState({latitude,longitude},() => {
                    _this.llToAddress();
                })
            }
        }) 
    }
    setCenterLocal(){
        var _this = this;
        this.mapCtx = Taro.createMapContext("tx-map",this);
        this.mapCtx.getCenterLocation({
            type: 'gcj02',
            success: function(res) {
                _this.setState({
                    latitude: res.latitude,
                    longitude: res.longitude,
                },() => {
                    _this.llToAddress();
                })
            }
        })
    }
    llToAddress(){ //坐标转汉字
        let _this = this;
        let { latitude , longitude } = this.state;
        _this.qqmapsdk.reverseGeocoder({
            //位置坐标，默认获取当前位置，非必须参数
            /**
             //Object格式
              location: {
                latitude: 39.984060,
                longitude: 116.307520
              },
            */
            location: {latitude,longitude},
            success: function(res) {//成功后的回调
                let address = res.result.address;
                let city = res.result.address_component.city
                _this.setState({address,city})
            },
            fail: function(error) {
                console.error(error);
            },
          })
    }
    AddressToll(address){ //汉字转坐标
        let _this = this;
        _this.qqmapsdk.geocoder({
            //获取表单传入地址
            address:address, //地址参数，例：固定地址，address: '北京市海淀区彩和坊路海淀西大街74号'
            success: function(res) {//成功后的回调
                var res = res.result;
                var latitude = res.location.lat;
                var longitude = res.location.lng;
                var address = res.address_components.province + res.address_components.city + res.address_components.district;
                _this.setState({address,longitude,latitude})
            },
          })

    }
    computedSvheight(){ //计算scrollview的高度
        var _this = this;
        var query = wx.createSelectorQuery();
        //选择id
        query.select('#mpct').boundingClientRect()
        query.exec(function (res) {
            //res就是 所有标签为mjltest的元素的信息 的数组
            console.log(res);
        })
    }
    submitAddress(){
        let { lastPargeParam , address , latitude ,  longitude , oftStatus } = this.state;
        Taro.eventCenter.trigger('addressSelect',lastPargeParam,{address,latitude,longitude})
        Taro.navigateBack();
    }
    render(){
        let { longitude , latitude , address , listOpen , city , oftAddress} = this.state;
        return (
            <View className='map-container flex flex-wrap ' id='mpct'>
                <View className='address flex align-items space-between'>
                    <View className='pro fn-ctr'>
                        <Text className='txt1' onClick={this.selectCity.bind(this)}>{city}</Text>
                        <Text className='iconfont iconf11'></Text>
                    </View>
                    <View className='dtl flex1 ell1'>
                        <AtInput
                            name='value'
                            type='text'
                            clear
                            placeholder='请输入地址'
                            value={address}
                            onChange={this.onAddressChange.bind(this)}
                        />
                    </View>   
                </View>
                <Map id='tx-map'  className='map_ct flex1'
                    longitude={longitude}
                    latitude={latitude}
                    onClick={this.onTap} 
                    onRegionchange={ e => this.onMapMove(e)}
                />
                <Image className='dingwei' src={`${baseImgSrc}/map_icon.png`} />
                {
                    oftStatus ? (
                        <View className='address-list'>
                            <View className='title'></View>
                            {
                                oftAddress.map(v => (
                                    <View className='item flex align-items flex-start' onClick={this.clickOftAddress.bind(this,v.address,v.location.lat,v.location.lng)}>
                                        <Text className='iconfont iconlocation'></Text>
                                        <Text className='item-txt'>{v.address}</Text>
                                    </View>
                                )) 
                            }
                        </View>
                    ) : ""
                }
                <AtButton className='map-btn' type='primary' size='normal' onClick={this.submitAddress.bind(this)}>确定</AtButton>
                {
                    listOpen ? (
                        <View style='height:100vh' className='city-list'>
                            <AtIndexes
                            list={cityData}
                            onClick={this.onCityItem.bind(this)}
                            >
                            <View className='city-list-title flex align-items space-between'>
                                <Text>热门城市</Text>
                                <Text className='iconfont iconguanbi2' onClick={this.closeCity.bind(this)}></Text>
                            </View>
                            </AtIndexes>
                        </View>
                    ) : ''
                }
            </View>
        )
    }
}